//
//  POISearchViewController.m
//  rrbi
//
//  Created by mac book on 2018/12/14.
//

#import "POISearchViewController.h"

#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>



//
#import "TBPoiListView.h"

#import "TBSearchKeyWordsPoiListView.h"

#import "POIRequest.h"

#import "TBPoiSearchView.h"

#define view_Height ([UIScreen mainScreen].bounds.size.height - 60 -64)


#define Top_Height (60)

@interface POISearchViewController ()

<MAMapViewDelegate,TBPoiListViewDelegate,TBPoiSearchViewDelegate,TBSearchKeyWordsPoiListViewDelegate>
//中间定位view
@property (strong, nonatomic) UIImageView *centerlocationView;
//图片
@property (strong, nonatomic) UIImage *img;
//地图
@property (strong, nonatomic)  MAMapView *mapView;
//poi 数组
@property (strong,nonatomic) NSArray *poi_arr;
//刷新按钮
@property (strong, nonatomic) UIButton *refreshBtn;
//底部弹出列表
@property (strong, nonatomic) TBPoiListView *listView;


//查询视图
@property (strong, nonatomic) TBPoiSearchView *searchView;

//搜索关键字列表
@property (strong, nonatomic) TBSearchKeyWordsPoiListView *WordsPoiListView;
//poi搜索请求
@property (strong, nonatomic) POIRequest *poiRequest;

@end

@implementation POISearchViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor whiteColor];
    
    //    self.navigationController.navigationBar.translucent = NO;
    
    [AMapServices sharedServices].apiKey = AMap_ApiKey;
    
    
    //    ///地图需要v4.5.0及以上版本才必须要打开此选项（v4.5.0以下版本，需要手动配置info.plist）
    [AMapServices sharedServices].enableHTTPS = YES;
    
    //MARK: 初始化地图
    //初始化地图
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(0, Top_Height, [UIScreen mainScreen].bounds.size.width, view_Height/2)];
    
    self.mapView.delegate = self;
    //把地图添加至view
    [self.view addSubview:self.mapView];
    
    //如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    _mapView.zoomLevel = 14.0;
    
    //屏幕中心点--自定义
    self.img = [UIImage imageNamed:@"icon_repair_location"];
    
    self.centerlocationView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.img.size.width, self.img.size.height)];
    self.centerlocationView.image = self.img;
    self.centerlocationView.center = CGPointMake(_mapView.center.x, _mapView.center.y - self.img.size.height/2);
    
    [self.view addSubview:self.centerlocationView];
    
    //添加tableView 到view
    [self.view addSubview:self.listView];
    
    //MARK: 回到当前定位按钮
    self.refreshBtn = [UIButton buttonWithType:0];
    
    self.refreshBtn.frame = CGRectMake(CGRectGetMaxX(_mapView.frame) - 50, CGRectGetMaxY(_mapView.frame) - 50, 30, 30);
    
    [self.refreshBtn addTarget:self action:@selector(btnHandler) forControlEvents:(UIControlEventTouchUpInside)];
    [self.refreshBtn setImage:[UIImage imageNamed:@"icon_location"] forState:UIControlStateNormal];
//    self.refreshBtn.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.refreshBtn];
    
    
    self.searchView = [[TBPoiSearchView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 60)];
    self.searchView.delegate = self;
    self.searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.WordsPoiListView];
    self.WordsPoiListView.hidden = YES;
    //MARK: 搜索
    self.poiRequest = [[POIRequest alloc] init];
    
    __weak typeof(self) weakSelf = self;
    
    [self.poiRequest searchRequestCLLocationCoordinate2D:CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude ,_mapView.centerCoordinate.longitude) keyWords:@"楼宇 | 写字楼 | 住宅 | 商场" cityName:self.searchView.cityBtn.titleLabel.text complation:^(NSArray *arr) {
        
        [weakSelf.listView updataDataSource:arr];
    }];
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    //    [super viewWillAppear:YES];
    //
    self.mapView.frame = CGRectMake(0, Top_Height, [UIScreen mainScreen].bounds.size.width, view_Height/2);
    
    
}
#pragma mark -- 当前定位位置显示到屏幕中间
- (void)btnHandler{
    
    if (_mapView.centerCoordinate.latitude != _mapView.userLocation.location.coordinate.latitude ||  _mapView.centerCoordinate.longitude != _mapView.userLocation.location.coordinate.longitude) {
        [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate animated:YES];
        
    }
    
    
}


#pragma mark -- <MAMapViewDelegate>
/**
 * @brief 地图移动结束后调用此接口
 * @param mapView       地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction{
    
    NSLog(@"%.2f   %.2f",mapView.centerCoordinate.longitude,mapView.centerCoordinate.latitude);
    
    //通过设置参数即可改变不同的状态；
    [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:1 initialSpringVelocity:0 options:UIViewAnimationOptionTransitionNone animations:^{
        self.centerlocationView.center = CGPointMake(mapView.center.x, mapView.center.y - self.img.size.height);
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:0.3 animations:^{
            self.centerlocationView.center = CGPointMake(mapView.center.x, mapView.center.y - self.img.size.height/2);
            
        }];
        
        
    }];
    
    
    __weak typeof(self) weakSelf = self;
    
    [self.poiRequest searchRequestCLLocationCoordinate2D:CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude ,_mapView.centerCoordinate.longitude) keyWords:@"楼宇 | 写字楼 | 住宅 | 商场" cityName:self.searchView.cityBtn.titleLabel.text complation:^(NSArray *arr) {
        
        [weakSelf.listView updataDataSource:arr];
    }];
}



- (TBPoiListView *)listView{
    if (!_listView) {
        _listView = [[TBPoiListView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_mapView.frame), CGRectGetWidth(_mapView.frame), CGRectGetHeight(_mapView.frame))];
        _listView.delegate = self;
    }
    
    return _listView;
}

- (TBSearchKeyWordsPoiListView *)WordsPoiListView{
    if (!_WordsPoiListView) {
        _WordsPoiListView = [[TBSearchKeyWordsPoiListView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), CGRectGetWidth(_mapView.frame), view_Height)];
        
        
        _WordsPoiListView.delegate = self;
        
        _WordsPoiListView.backgroundColor = [UIColor blackColor];
        _WordsPoiListView.alpha = 0.6;
    }
    
    return _WordsPoiListView;
}

- (void)poiListScrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat temp = view_Height/8;
    
    if (scrollView.contentOffset.y >0) {
        
        [UIView animateWithDuration:0.5 animations:^{
            
            
            
            self.mapView.frame = CGRectMake(0, Top_Height-temp, [UIScreen mainScreen].bounds.size.width, view_Height/2);
            
            self.centerlocationView.center = CGPointMake(self.mapView.center.x, self.mapView.center.y - self.img.size.height/2);
            
            
            
            self->_listView.frame = CGRectMake(0, CGRectGetMaxY(self->_mapView.frame) -temp, CGRectGetWidth(self->_mapView.frame), CGRectGetHeight(self->_mapView.frame) + 2*temp);
            self.refreshBtn.frame = CGRectMake(CGRectGetMaxX(self->_mapView.frame) - 50, CGRectGetMaxY(self->_mapView.frame)  -50 -temp, 30, 30);
            
            
        }];
        
    }else{
        
        [UIView animateWithDuration:0.5 delay:0 options:(UIViewAnimationOptionBeginFromCurrentState) animations:^{
            self.mapView.frame = CGRectMake(0, Top_Height, [UIScreen mainScreen].bounds.size.width, view_Height/2);
            self.centerlocationView.center = CGPointMake(self.mapView.center.x, self.mapView.center.y - self.img.size.height/2);
            
            self.refreshBtn.frame = CGRectMake(CGRectGetMaxX(self->_mapView.frame) - 50, CGRectGetMaxY(self->_mapView.frame) - 50, 30, 30);
            self->_listView.frame = CGRectMake(0, CGRectGetMaxY(self->_mapView.frame), CGRectGetWidth(self->_mapView.frame), CGRectGetHeight(self->_mapView.frame) + 2*temp);
            
            
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                
                self->_listView.frame = CGRectMake(0, CGRectGetMaxY(self->_mapView.frame), CGRectGetWidth(self->_mapView.frame), CGRectGetHeight(self->_mapView.frame) );
                
                
            }];
        }];
        
        
        
        
        
    }
    
}


- (void)backDataWith:(NSDictionary *)dic{
    //回调返回字典数据
    
    self.returnPoiData(dic);
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark -- TBPoiListViewDelegate
- (void)tb_ListViewDidselectPoiList:(NSDictionary *)dic{
    //点击poi后的回调
    [self backDataWith:dic];
}

#pragma mark -- TBSearchKeyWordsPoiListViewDelegate
- (void)tb_KeyWordsDidselectPoiList:(NSDictionary *)dic{
    //搜索后 点击poi后的回调
    [self backDataWith:dic];
}




#pragma mark --- TBPoiSearchViewDelegate
- (BOOL)tb_SearchBarShouldBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    [UIView animateWithDuration:0.5 animations:^{
        self.WordsPoiListView.hidden = NO;
    }];
    return YES;
}
- (void)tb_SearchBarCancelButtonClicked:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
    __weak typeof(self) weakSelf = self;
    searchBar.text = @"";
    [self.WordsPoiListView updataDataSource:@[]];
    
    [UIView animateWithDuration:0.5 animations:^{
        weakSelf.WordsPoiListView.hidden = YES;
        weakSelf.WordsPoiListView.backgroundColor = [UIColor blackColor];
        weakSelf.WordsPoiListView.alpha = 0.6;
    }];
    
    
    [searchBar resignFirstResponder];
    
}

- (void)tb_SearchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    
    NSLog(@"%@",searchBar.text);
    
    __weak typeof(self) weakSelf = self;
    
    [self.poiRequest searchRequestCLLocationCoordinate2D:CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude ,_mapView.centerCoordinate.longitude) keyWords:searchBar.text cityName:self.searchView.cityBtn.titleLabel.text complation:^(NSArray *arr) {
        if (arr.count == 0) {
            weakSelf.WordsPoiListView.backgroundColor = [UIColor whiteColor];
            weakSelf.WordsPoiListView.alpha = 0.6;
        }else{
            
            [weakSelf.WordsPoiListView updataDataSource:arr];
            weakSelf.WordsPoiListView.alpha = 1;
            [weakSelf.WordsPoiListView updataDataSource:arr];
        }
        
        
    }];
    
    
}


- (void)tb_SearchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    searchBar.showsCancelButton = NO;
    [searchBar resignFirstResponder];
    
    __weak typeof(self) weakSelf = self;
    
    
    [self.poiRequest searchRequestCLLocationCoordinate2D:CLLocationCoordinate2DMake(_mapView.centerCoordinate.latitude ,_mapView.centerCoordinate.longitude) keyWords:searchBar.text cityName:self.searchView.cityBtn.titleLabel.text complation:^(NSArray *arr) {
        if (arr.count == 0) {
            weakSelf.WordsPoiListView.backgroundColor = [UIColor blackColor];
            weakSelf.WordsPoiListView.alpha = 0.6;
        }else{
            weakSelf.WordsPoiListView.backgroundColor = [UIColor whiteColor];
            weakSelf.WordsPoiListView.alpha = 1;
            [weakSelf.WordsPoiListView updataDataSource:arr];
        }
        
        
    }];
    
    
    
}

- (void)tb_TapCityBtnhHandler:(UIButton *)button{
    NSLog(@"选择城市");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
